import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
// Do something before request is sent
  if (store.getters.token && config.url !== '/auth/local/register') {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(response => {
// Do something before response is sent
  return response
}, error => {
// Do something with response error
  console.dir(error)

  if (error.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error('登录超时，请重新登录！')
  }

  return Promise.reject(error)
})

export default service
